import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { hash, verify } from 'argon2';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwt: JwtService,
  ) {}

  // 注册
  async register(dto) {
    console.log(dto);

    const user = await this.prisma.user.create({
      data: {
        name: dto.name,
        password: await hash(dto.password),
      },
    });    
    return this.token(user);
  }
  
  // token
   private async  token({ id, name }: any) {
    return {
      token: await this.jwt.signAsync({
        name,
        sub: id,
      }),
    };
  }


  async login(dto){
      const   user = await this.prisma.user.findUnique({
        where:{
          name:dto.name
        }
      })

if(!(await verify(user.password,dto.password))){
   throw new BadRequestException('密码输入不正确')
}      
      return this.token(user)
  }
}
